<?php

namespace App\Http\Controllers\Entity\tag_content;

use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\tag_content\tag_contentRequest;
use App\Models\Entity\sys_categories\sys_categories;
use App\Models\Entity\Tag\tag;
use App\Repositories\Entity\Tag\tagRepository;
use App\Models\Entity\tag_content\tag_content;
use App\Repositories\Entity\tag_content\tag_contentRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;


class tag_contentController extends Controller
{
    use ModelForm;

    /** @var  tag_contentRepository */
    private $tagContentRepository;

    /** @var  tagRepository */
    private $tagRepository;

    public function __construct(tag_contentRepository $tagContentRepo,tagRepository $tagRepo)
    {
        $this->tagContentRepository = $tagContentRepo;
        $this->tagRepository = $tagRepo;
    }

    /**
     * Display a listing of the tag_content.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.tag_content.tag_contents.index_header'));
            $content->description(__('entity.tag_content.tag_contents.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new tag_content.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.tag_content.tag_contents.create_header'));
            $content->description(__('entity.tag_content.tag_contents.create_description'));

            $content->body($this->form());

        });
    }

    /**贴标签
     * Store a newly created tag_content in storage.
     *
     * @param tag_contentRequest $request
     *
     * @return Response
     */
    public function store(tag_contentRequest $request)
    {
        $input = $request->all();
        $tag_content_id = $request->input('tag_content_id');
        $tag_content_id = is_array($tag_content_id) ? $tag_content_id : (strpos($tag_content_id,',') ? explode(',',$tag_content_id) : $tag_content_id);
        $tag_id = $request->input('tag_id');
        $tag_content_type = $request->input('tag_content_type');
        // 判断是否为批量贴标签
        if (is_array($tag_content_id) && is_array($tag_id)) {
            foreach ($tag_content_id as $value) {
                foreach ($tag_id as $v){
                    $flag = tag_content::where(['tag_id' => $v, 'tag_content_id' => $value, 'tag_content_type' => $tag_content_type])->first();
                    if ($flag) {
                        continue;
                    } else {
                        $tag_content    = new tag_content();
                        $tag_content->tag_id = $v;
                        $tag_content->tag_content_type   = $tag_content_type;
                        $tag_content->tag_content_id   = $value;
                        $tag_content->save();
                    }
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }elseif(is_array($tag_content_id) && !is_array($tag_id)){
            foreach ($tag_content_id as $value) {
                $flag = tag_content::where(['tag_id' => $tag_id, 'tag_content_id' => $value, 'tag_content_type' => $tag_content_type])->first();

                if ($flag) {
                    continue;
                } else {
                    $tag_content    = new tag_content();
                    $tag_content->tag_id = $tag_id;
                    $tag_content->tag_content_type   = $tag_content_type;
                    $tag_content->tag_content_id   = $value;
                    $tag_content->save();
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }elseif(!is_array($tag_content_id) && is_array($tag_id)){
            // 判断是否为批量打标签
                foreach ($tag_id as $value) {
                    $flag = tag_content::where(['tag_id' => $value, 'tag_content_id' => $tag_content_id, 'tag_content_type' => $tag_content_type])->first();

                    if ($flag) {
                        continue;
                    } else {
                        $tag_content    = new tag_content();
                        $tag_content->tag_id = $value;
                        $tag_content->tag_content_type   = $tag_content_type;
                        $tag_content->tag_content_id   = $tag_content_id;
                        $tag_content->save();
                    }
                }
                return response()->json(['content' => '添加成功！', 'status' => true]);
        }elseif(!is_array($tag_content_id) && !is_array($tag_id)){
            //贴标签
            $flag = tag_content::where(['tag_id' => $tag_id, 'tag_content_id' => $tag_content_id, 'tag_content_type' => $tag_content_type])->first();

            if ($flag) {
                return response()->json(['content' => '不能重复贴标签,标签已存在！', 'status' => false]);
            }

            $tagContent = $this->tagContentRepository->create($input);

            Flash::success(__('entity.tag_content.tag_contents.saved_success'));

            return response()->json(['content' => '添加成功！', 'status' => true]);
        }

        //return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.tag_content.tag_contents.index'));

    }

    /*
     * 批量打标签
     *
     */
    public function moreStore(tag_contentRequest $request)
    {
        $input = $request->all();


        $tagContent = $this->tagContentRepository->create($input);

        Flash::success(__('entity.tag_content.tag_contents.saved_success'));

        return response()->json(['content' => '添加成功！', 'status' => true]);

        //return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.tag_content.tag_contents.index'));

    }

    /**
     * Display the specified tag_content.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $tagContent = $this->tagContentRepository->findWithoutFail($id);

        if (empty($tagContent)) {
            Flash::error(__('entity.tag_content.tag_contents.not_found'));

            return redirect(route('entity.tag_content.tag_contents.index'));
        }

        return view('entity.tag_content.tag_contents.show')->with('tagContent', $tagContent);

    }

    /**
     * Show the form for editing the specified tag_content.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {


        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.tag_content.tag_contents.edit_header'));
            $content->description(__('entity.tag_content.tag_contents.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified tag_content in storage.
     *
     * @param  int              $id
     * @param tag_contentRequest $request
     *
     * @return Response
     */
    public function update($id, tag_contentRequest $request)
    {
        $tagContent = $this->tagContentRepository->findWithoutFail($id);

        if (empty($tagContent)) {
            Flash::error(__('entity.tag_content.tag_contents.not_found'));

            return redirect(route('entity.tag_content.tag_contents.index'));
        }
        $input = $request->all();

        $tagContent = $this->tagContentRepository->update($input, $id);


        Flash::success(__('entity.tag_content.tag_contents.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.tag_content.tag_contents.index'));
    }

    /**
     * Remove the specified tag_content from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->tagContentRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('entity.tag_content.tag_contents.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $tagContent = $this->tagContentRepository->findWithoutFail($id);

        if (empty($tagContent)) {
            Flash::error(__('entity.tag_content.tag_contents.not_found'));

            return redirect(route('entity.tag_content.tag_contents.index'));
        }

        if ($flag = $this->tagContentRepository->delete($id)) {


            return response()->json(['message' => __('entity.tag_content.tag_contents.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * Delete from database table;
     *
     * @param  int $id
     *
     * @return Response
     */
    public function delete(Request $request)
    {
        $id = $request->input('id');
        // 判断是否为批量删除
        if (is_array($id)) {
           $flag = tag_content::whereIn('id', $id)->forceDelete();
        }else{
            $flag = tag_content::where(['id' => $id])->forceDelete();
        }

        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => true]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => false]);

        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(tag_content::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('tag_id', '标签ID');
            $form->select('content_model', '内容模型');
            $form->text('content_id', '内容ID');


            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(tag_content::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('entity.tag_content.tag_contents.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('entity.tag_content.tag_contents.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('entity.tag_content.tag_contents.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('entity.tag_content.tag_contents.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('entity.tag_content.tag_contents.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('entity.tag_content.tag_contents.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.tag_content.tag_contents.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.tag_content.tag_contents.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.tag_content.tag_contents.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.tag_content.tag_contents.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('tag_id', '标签ID')->sortable();
            $grid->column('content_model', '内容模型')->sortable();
            $grid->column('content_id', '内容ID')->sortable();



            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('tag_name', '标签名称');

            });
        });
    }


    public function selectedContent(Request $request)
    {
            /**
             * 过滤字段
             */

            // 搜索框的值
            $search_value = $request->all('search_value');
            // 二级栏目id
            $tag_id = $request->all('tag_id');
            // 收费类型
            $charge_type = $request->all('charge_type');

            //$taginfo = tag::with(['vasseti'])->find($tag_id);
            //print_r($taginfo);
            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');

            $model_tag_content = new tag_content();
            $where = array('tag_id'=>$tag_id);
            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }
            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            list($data['recordsTotal'], $data['recordsFiltered'],$data['data']) = $model_tag_content->tagContentList($where,$start,$length,$ord);
            return response()->json($data);

    }



}
